package com.xianyun.site.support.executor.filter.smtp;


import com.xianyun.common.core.filter.Filter;
import com.xianyun.common.core.filter.FilterInvoker;
import com.xianyun.common.redis.service.RedisService;
import com.xianyun.site.support.common.constant.MessageConstants;
import com.xianyun.site.support.common.constant.SmtpServiceConstants;
import com.xianyun.site.support.common.exception.SmtpErrorCode;
import com.xianyun.site.support.common.exception.SmtpException;
import com.xianyun.site.support.convertor.SmtpConvertor;
import com.xianyun.site.support.domain.model.SmtpMessage;
import com.xianyun.site.support.dto.SmtpReceiveCmd;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author mac_zyj
 */
@Slf4j
@Component
public class EmailSendTooMuchFilter implements Filter<SmtpReceiveCmd> {

    @Autowired
    private RedisService redisService;


    @Override
    public void doFilter(SmtpReceiveCmd context, FilterInvoker nextFilter) {
        SmtpMessage message = SmtpConvertor.toEntity(context.getSmtpMessage());
        String redisCheckKey = message.getRedisCheckKey(MessageConstants.TIMES_CHECK);
        Integer sendTimesInLastHour=redisService.getCacheObject(redisCheckKey);
        if(null!=sendTimesInLastHour){
            if (sendTimesInLastHour>SmtpServiceConstants.CHECK_SMTP_SEND_TIMES_TIMES_LIMITS) {
                String errorCode=SmtpErrorCode.EMAIL_SEND_TOO_MUCH_ERROR.getErrCode();
                log.info(SmtpErrorCode.EMAIL_SEND_TOO_MUCH_ERROR.getErrCode()+"-------"+message.getToAddress());
                throw new SmtpException(errorCode);
            }
        }
        nextFilter.invoke(context);
    }
}
